﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.Commerce.Promotions.DiscountByCategory.Models;
using Kooboo.IoC;

namespace Kooboo.Commerce.Promotions.DiscountByCategory.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class DiscountByCategoryController : Controller
    {
        //
        // GET: /DiscountByCategory/
        public ActionResult Index(int id)
        {
            int? selectedReduceType = null;
            ICategory selectedCategory = null;
            var rule = Services.Current.Find(id);
            if (rule == null)
            {
                rule = new Promotion_DiscountByCategory
                {
                    DiscountRuleId = id
                };
            }
            else
            {
                selectedReduceType = rule.ReduceType;
                selectedCategory = ObjectContainer.CreateInstance<ICategory>();
                selectedCategory.Id = rule.CategoryId;
            }

            var categoriesContext = ContextContainer.Current.Resolve<ICategoryRepository>();
            var firstLevelCategories = categoriesContext.Categories.Where(c => c.Parent == null);

            ViewData["CategoryContainerID"] = "CategoryId";
            ViewData["BindingCategories"] = CreateBindingCategories(firstLevelCategories, selectedCategory == null ? null : new ICategory[] { selectedCategory });

            ViewData["ReduceType"] = EnumHelper.ConvertEnumToSelectListItem<ReduceType>(selectedReduceType);
            return View(rule);
        }

        [HttpPost]
        public ActionResult Index(Promotion_DiscountByCategory promotion, String next)
        {
            if (next == "prev")
            {
                return Json(new { Data = this.Url.Action("Edit", "PromotionRule", new { Id = promotion.DiscountRuleId }) });
            }
            else
            {
                if (promotion.ReduceType == (int)ReduceType.ByFee && promotion.ReduceValue <= 0)
                {
                    return Json(new { Error = "Please enter a valid discount fee" });
                }

                if (promotion.ReduceType == (int)ReduceType.ByPercent && (promotion.ReduceValue < 0 || promotion.ReduceValue > 1))
                {
                    return Json(new { Error = "Please enter a valid discount fee" });
                }

                if (promotion.CategoryId < 1)
                {
                    return Json(new { Error = "Please choose a category" });
                }

                var rule = Services.Current.DataContext.Promotion_DiscountByCategories.Where(d => d.DiscountRuleId == promotion.DiscountRuleId).FirstOrDefault();
                if (rule == null)
                {
                    rule = new Promotion_DiscountByCategory()
                    {
                        DiscountRuleId = promotion.DiscountRuleId
                    };
                    Services.Current.DataContext.Promotion_DiscountByCategories.InsertOnSubmit(rule);
                }

                rule.ReduceType = promotion.ReduceType;
                rule.ReduceValue = promotion.ReduceValue;
                rule.CategoryId = promotion.CategoryId;
                Services.Current.DataContext.SubmitChanges();

                return Json(new { Data = this.Url.Action("Index", "PromotionRule") });
            }
        }


        /// <summary>
        /// combian categories and selected categories to a new object
        /// </summary>
        /// <param name="allCategories"></param>
        /// <param name="selectedCategories"></param>
        /// <returns></returns>
        private IEnumerable<BindingCategory> CreateBindingCategories(IEnumerable<ICategory> categories,
            IEnumerable<ICategory> selectedCategories, ICategory removeCategory = null)
        {
            if (categories != null && categories.Count() > 0)
            {
                if (removeCategory != null)
                {
                    categories = categories.Where(c => c.Id != removeCategory.Id);
                }

                if (selectedCategories == null || selectedCategories.Count() == 0)
                {
                    return categories
                        .Select(c =>
                        new BindingCategory()
                        {
                            ID = c.Id,
                            Name = c.Name,
                            Selected = "",
                            Children = CreateBindingCategories(c.Children, selectedCategories, removeCategory)
                        });
                }
                else
                {
                    return categories.Select(c =>
                           new BindingCategory()
                           {
                               ID = c.Id,
                               Name = c.Name,
                               Selected = (selectedCategories.Where(sc => sc.Id == c.Id).Count() > 0 ? "checked" : ""),
                               Children = CreateBindingCategories(c.Children, selectedCategories, removeCategory)
                           });
                }
            }
            else
            {
                return Enumerable.Empty<BindingCategory>();
            }
        }

    }
}
